package com.szqhyxj.youxiangju.biz.receivables;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szqhyxj.youxiangju.BaseActivity;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.core.UserInfo;
import com.szqhyxj.youxiangju.biz.core.UserInfoManger;
import com.szqhyxj.youxiangju.biz.web.WebActivity;
import com.szqhyxj.youxiangju.sys.components.ChoiceReceivablePopView;
import com.szqhyxj.youxiangju.sys.components.NavigationBar;
import com.szqhyxj.youxiangju.sys.components.androidpicker.qqtheme.framework.picker.OptionPicker;
import com.szqhyxj.youxiangju.sys.components.androidpicker.qqtheme.framework.util.PickerUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by leung on 2019/1/4.
 */

public class ReceivablesActivity extends BaseActivity implements ReceivablesContract.ReceivablesView, NavigationBar.NavigationBarListener {
    private static String BALANCE = "balance";
    @BindView(R.id.navigationBar)
    NavigationBar navigationBar;
    @BindView(R.id.liftingamount)
    TextView liftingamount;
    @BindView(R.id.amount)
    EditText amount;
    @BindView(R.id.accountbalance)
    TextView accountbalance;
    @BindView(R.id.billingcard)
    TextView billingcard;
    @BindView(R.id.startReceivables)
    TextView startReceivables;
    @BindView(R.id.tip)
    TextView tips;
    @BindView(R.id.IssuingbankTitle)
    TextView IssuingbankTitle;
    @BindView(R.id.IssuingbankIcon)
    TextView IssuingbankIcon;
    @BindView(R.id.IssuingbankArea)
    LinearLayout IssuingbankArea;
    @BindView(R.id.depositCard)
    EditText depositCard;
    @BindView(R.id.cardPhone)
    EditText cardPhone;
    @BindView(R.id.verificationCode)
    EditText verificationCode;
    @BindView(R.id.acquire)
    TextView acquire;
    private String balance;
    Map<String, String> map;

    ReceivablesPresenter presenter;
    public static final String USERCARDINFO = "userCardInfo";
    private static SharedPreferences.Editor editor;
    private static SharedPreferences shared;

    public static void start(Activity activity, String balance) {
        Intent intent = new Intent();
        intent.setClass(activity, ReceivablesActivity.class);
        intent.putExtra(BALANCE, balance);
        activity.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receivables);
        ButterKnife.bind(this);
        balance = getIntent().getStringExtra(BALANCE);
        navigationBar.setNavigationBarListener(this);
        presenter = new ReceivablesPresenter(this);
        accountbalance.setText(balance + "元");
        shared = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        editor = shared.edit();
        getUserCardInfo();
        // presenter.getCard();
        amount.setTextSize(15);
        map = new HashMap();
        amount.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                amount.setTextSize(25);
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        amount.setText(s);
                        amount.setSelection(s.length());
                    }
                } //如果.在起始位置,则起始位置自动补0
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    amount.setText(s);
                    amount.setSelection(2);
                }
                //如果起始位置为0并且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        amount.setText(s.subSequence(0, 1));
                        amount.setSelection(1);
                        return;
                    }
                }

                presenter.setAmount(s.toString(), balance);
            }
        });
        verificationCode.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                presenter.setVerificationCode(s + "");
            }
        });
        depositCard.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                presenter.setBankCard(s + "");
            }
        });
        cardPhone.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                presenter.setCardPhone(s + "");
            }
        });
    }

    public void getUserCardInfo(){
        String json =   shared.getString(UserInfoManger.INSTANCE.getUser().getUseraccount(),"");
        Log.e("查询到的数据",json+"");
        if (json.equals("")){
            return;
        }
        Gson gson = new Gson();
        map = new Gson().fromJson(json, new TypeToken<HashMap<String,Object>>(){}.getType());
        IssuingbankTitle.setText(map.get(BTNAME));
        IssuingbankTitle.setTextColor(getResources().getColor(R.color.black));
        depositCard.setText(map.get(CARDNO));
        cardPhone.setText(map.get(CARDPHONE));
        presenter.setBtName(map.get(BTNAME));
        presenter.setBtCode(map.get(BTCODE));
        presenter.setCardPhone(map.get(CARDPHONE));
        presenter.setBankCard(map.get(CARDNO));


    }

    @Override
    public void showEnClickable() {
        startReceivables.setEnabled(false);
        startReceivables.setBackground(getResources().getDrawable(R.drawable.background_btn_grey04));
    }

    @Override
    public void showClickable() {
        startReceivables.setEnabled(true);
        startReceivables.setBackground(getResources().getDrawable(R.drawable.background_btn04));
    }

    @Override
    public void showsavaCard(String cardinfo) {
        billingcard.setText(cardinfo);
    }

    @Override
    public void showReceivablesDetail(String withdrawId) {
        presenter.getUserInfo();
        WebActivity.startToH5(this, "withdrawDetail?withdrawId=" + withdrawId);
        finish();
    }

    @Override
    public void setTip(String tip) {
        tips.setText(tip);
        tips.setTextColor(getResources().getColor(R.color.textcolor4e));
    }

    @Override
    public void setTip1(String tip) {
        tips.setText(tip);
        tips.setTextColor(getResources().getColor(R.color.textcolor66));
    }

    @Override
    public void showTextSize() {
        amount.setTextSize(15);
    }

    private String issuingBank;  //发卡行
    private String btCode;  //发卡行code

    @Override
    public void showSupportBankList(List<ReceivablesModel.Response> lists) {
        String[] bs = new String[lists.size()];
        for (int i = 0; i < lists.size(); i++) {
            bs[i] = lists.get(i).getBankName();
        }
        PickerUtil.onOptionPicker(this, bs, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                IssuingbankTitle.setText(item);
                IssuingbankTitle.setTextColor(getResources().getColor(R.color.black));
                issuingBank = item;
                btCode = lists.get(index).getBtCode();
                presenter.setBtName(issuingBank);
                presenter.setBtCode(btCode);
                IssuingbankIcon.setVisibility(View.GONE);
                Log.e("------------", "选择了" + issuingBank + "--" + btCode);
            }
        });
    }

    @Override
    public void showAcquiredVerificationCodeSuccess() {
        Toast.makeText(this, "验证码已发送", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showAcquiringVerificationCode(int min) {
        acquire.setText(String.format("%ss", String.valueOf(min)));
        acquire.setEnabled(false);
    }

    @Override
    public void showAcquiredVerificationCode() {
        acquire.setText("发送");
        acquire.setEnabled(true);
    }

    private static String BTCODE = "btCode";
    private static String BTNAME = "btName";
    private static String CARDNO = "cardNo";
    private static String CARDPHONE = "cardPhone";

    @Override
    public void addBean(ReceivablesModel.Receivables receiptEntity) {
        String key = shared.getString(UserInfoManger.INSTANCE.getUser().getUseraccount(),"");
        if (key.equals("")){
            map.put(BTCODE, receiptEntity.getBtCode());
            map.put(BTNAME, receiptEntity.getBtName());
            map.put(CARDNO, receiptEntity.getBankCardNo());
            map.put(CARDPHONE, receiptEntity.getPhone());
            Gson gson = new Gson();
            String json = gson.toJson(map);
            editor.putString(UserInfoManger.INSTANCE.getUser().getUseraccount(), json + "");
            editor.commit();
            Log.e("map转String", json);
        }else{
            editor.remove(UserInfoManger.INSTANCE.getUser().getUseraccount());
            editor.commit();
            map.put(BTCODE, receiptEntity.getBtCode());
            map.put(BTNAME, receiptEntity.getBtName());
            map.put(CARDNO, receiptEntity.getBankCardNo());
            map.put(CARDPHONE, receiptEntity.getPhone());
            Gson gson = new Gson();
            String json = gson.toJson(map);
            editor.putString(UserInfoManger.INSTANCE.getUser().getUseraccount(), json + "");
            editor.commit();
            Log.e("map转String", json);
        }

    }


    @OnClick({R.id.liftingamount, R.id.startReceivables, R.id.IssuingbankArea, R.id.acquire})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.liftingamount:
                amount.setText(balance);
                break;
            case R.id.startReceivables:
                String money = amount.getText().toString();
                final ChoiceReceivablePopView outPopView = new ChoiceReceivablePopView(this, R.layout.popview_receivables);
                outPopView.show();
                outPopView.setOnClickListener(new ChoiceReceivablePopView.OnClickListener() {
                    @Override
                    public void onClickConfirm(View v) {
                        presenter.commit();
                        outPopView.dismiss();
                    }
                });
                break;
            case R.id.IssuingbankArea:
                presenter.getSupportBank();
                break;
            case R.id.acquire:
                presenter.acquireVerificationCode();
                break;
        }
    }


    public abstract static class SimpleTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @Override
    public void navigationLeft() {
        finish();
    }

    @Override
    public void navigationRight() {

    }


}
